package com.hamizhong.iflowers.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.hamizhong.iflowers.db.dao.hibernate.IAdminDao;
import com.hamizhong.iflowers.db.entity.Admin;
import com.hamizhong.iflowers.service.IAdminService;
import com.hamizhong.iflowers.service.base.MyBaseService;
import com.hamizhong.iflowers.utils.MD5Utils;
import com.hamizhong.iflowers.utils.MyTools;
import com.hamizhong.iflowers.web.dto.IOPResultDto;
import com.hamizhong.iflowers.web.vo.AdminVO;
import com.hamizhong.iflowers.web.vo.IObjectVO;

public class AdminServiceImpl extends MyBaseService implements IAdminService {
	private IAdminDao iAdminDao;

	public IAdminDao getiAdminDao() {
		return iAdminDao;
	}
	public void setiAdminDao(IAdminDao iAdminDao) {
		this.iAdminDao = iAdminDao;
	}
	public IOPResultDto<IObjectVO> doLoginADM(AdminVO adminVO) {
		IOPResultDto<IObjectVO> dto = new IOPResultDto<IObjectVO>();
		List<Admin> adminList = new ArrayList<Admin>();
		HashMap<String, Object> param = new HashMap<String, Object>();
		param.put("loginName", adminVO.getLoginName());
		adminList = iAdminDao.findByExample(param);
		if(adminList.size() > 0) {
			if(adminList.get(0).getLoginPassword().equals(MD5Utils.generateForAdminPassword(adminVO.getLoginPassword()))) {
				//设置登录时间和上次登录时间
				Admin updateAdmin = adminList.get(0);
				Date tempDate = updateAdmin.getThisLoginTime();
				updateAdmin.setThisLoginTime(new Date());
				updateAdmin.setLastLoginTime(tempDate);
				iAdminDao.update(updateAdmin);
				//设置返回的AdminVO
				AdminVO iAdminVO = new AdminVO();
				BeanUtils.copyProperties(updateAdmin, iAdminVO);
				iAdminVO.setLoginPassword("");
				IObjectVO iObjectVO = new IObjectVO();
				List<AdminVO> adminVOList = new ArrayList<AdminVO>();
				adminVOList.add(iAdminVO);
				iObjectVO.setAdminVOList(adminVOList);
				dto.addToResultList(iObjectVO);
				dto.setSuccess(true);
			}else {
				dto.setErrorMSG("对不起，账号或密码不正确！");
				dto.setSuccess(false);
			}
		}else {
			dto.setErrorMSG("对不起，账号或密码不正确！");
			dto.setSuccess(false);
		}
		return dto;
	}
	
	public IOPResultDto<IObjectVO> doUpdateAdminPassword(AdminVO adminVO) {
		IOPResultDto<IObjectVO> dto = new IOPResultDto<IObjectVO>();
		Admin admin = iAdminDao.findById(adminVO.getAdminId());
		if(admin == null) {
			dto.setErrorMSG("修改数据ID无效！");
			dto.setSuccess(false);
			return dto;
		}
		String oldPasswordMD5 = MD5Utils.generateForAdminPassword(adminVO.getLoginPassword());
		if(!admin.getLoginPassword().equals(oldPasswordMD5)) {
			dto.setErrorMSG("旧密码匹配错误！");
			dto.setSuccess(false);
			return dto;
		}
		admin.setLoginPassword(MD5Utils.generateForAdminPassword(adminVO.getNewPassword()));
		iAdminDao.update(admin);
		dto.setSuccess(true);
		return dto;
	}
	
}
